package com.tess.tboot.serviceimpl;


import com.tess.tboot.base.TbootServiceImpl;
import com.tess.tboot.common.constant.CommonConstant;
import com.tess.tboot.dao.mapper.UserMapper;
import com.tess.tboot.dao.mapper.UserRoleMapper;
import com.tess.tboot.entity.Role;
import com.tess.tboot.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 用户接口实现
 *
 * @author Exrickx
 */
@Slf4j
@Service
@Transactional
public class UserServiceImpl extends TbootServiceImpl<UserMapper, User> {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    public User findByUsername(String username) {

        List<User> list = userMapper.findByUsernameAndStatus(username, CommonConstant.USER_STATUS_NORMAL);
        if (list != null && list.size() > 0) {
            User user = list.get(0);
            List<Role> roleList = userRoleMapper.findByUserId(user.getId());
            user.setRoles(roleList);
            return user;
        }
        return null;
    }

    public List<User> findByStatusAndType(Integer status, Integer type) {

        return userMapper.findByStatusAndType(status, type);
    }


    public Page<User> findWithPage(Map<String, Object> params, Pageable pageable) {
//        Example example = new Example(User.class);
//        Example.Criteria criteria =
//                example.createCriteria();
//        if (null != params.get("username")) {
//            criteria.andLike("username", "%" + params.get("username").toString() + "%");
//        }
//        if (null != params.get("mobile")) {
//            criteria.andEqualTo("mobile", params.get("mobile").toString());
//        }
//        example.setOrderByClause("create_time desc");
//        int count = userMapper.selectCountByExample(example);
//        userMapper.selectByExampleAndRowBounds(example,rowBounds)
        int count = userMapper.findByCond(params);
        Page<User> page = new PageImpl<>(userMapper.findByCondWithPage(params,new RowBounds(pageable.getPageNumber(),pageable.getPageSize())),pageable,count);

        return page;

    }
}
